package httputil

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/tomnomnom/linkheader"
)

func Error(err error, msg string) interface{} {
	return struct {
		Err string `json:"err"`
		Msg string `json:"msg"`
	}{
		Err: err.Error(),
		Msg: msg,
	}
}

func Success(data interface{}) interface{} {
	return struct {
		Data interface{} `json:"data"`
	}{
		Data: data,
	}
}

func ReturnJson(code int64, message string, data interface{}) interface{} {
	return struct {
		Code    int64       `json:"code"`
		Message string      `json:"message"`
		Data    interface{} `json:"data"`
	}{
		Code:    code,
		Message: message,
		Data:    data,
	}
}

// Link:
// </products?page=5&perPage=20>;rel=self,
// </products?page=0&perPage=20>;rel=first,
// </products?page=4&perPage=20>;rel=previous,
// </products?page=6&perPage=20>;rel=next,
// </products?page=26&perPage=20>;rel=last
func writeLinks(req *http.Request, writer http.ResponseWriter, total, offset, limit int) {
	type LinkOffset struct {
		Link   string
		Offset int
	}
	offsets := []LinkOffset{
		{Link: "self", Offset: offset},
		{Link: "first", Offset: 0},
		{Link: "previous", Offset: offset - limit},
		{Link: "next", Offset: offset + limit},
		{Link: "last", Offset: total - total%limit},
	}

	qLink := url.Values{}
	qLink.Set("limit", fmt.Sprint(limit))

	links := linkheader.Links{}
	for _, linkOffset := range offsets {
		qLink.Set("offset", fmt.Sprint(linkOffset.Offset))
		links = append(links, linkheader.Link{
			URL: req.URL.Path + "?" + qLink.Encode(),
			Rel: linkOffset.Link,
		})
	}

	writer.Header().Set("Link", links.String())
}

// WritePagination to header
// x-total-count 列表总长度，用于分页
// x-query-limit 列表长度限制，用于分页。最大20
// x-query-offset 列表偏移，用于分页
func WritePagination(req *http.Request, writer http.ResponseWriter, total, offset, limit int) {
	writer.Header().Set("x-total-count", fmt.Sprint(total))
	writer.Header().Set("x-total-limit", fmt.Sprint(limit))
	writer.Header().Set("x-total-offset", fmt.Sprint(offset))
	writeLinks(req, writer, total, offset, limit)
}
